package com.vogue.supplymall.upload.domain.service.impl;

import com.qingstor.sdk.exception.QSException;
import com.vogue.ssm.database.entity.SnowflakeIdWorker;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.UploadInfo;
import com.vogue.supplymall.common.domain.tool.VerifyEnvironmentBean;
import com.vogue.supplymall.common.exception.RemoveUploadException;
import com.vogue.supplymall.common.exception.UploadException;
import com.vogue.supplymall.upload.domain.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import qingstor.util.QingstorService;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * The type Upload service.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-03-20
 */
@Service("uploadService")
public class UploadServiceImpl implements UploadService {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_UPLOADSERVICEIMPL = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Override
    public Boolean removeResource(UploadInfo uploadInfo) {
        return this.removeResource(uploadInfo.getDeletePath());
    }

    @Override
    public Boolean removeResource(String url) {
        if (url == null || url.length() == 0) {
            return true;
        }
        LOGGER_UPLOADSERVICEIMPL.info(">>> 删除上传文件 " + url);
        try {
            url = formatUrl(url);
            QingstorService.deleteFile(url);
        } catch (QSException e) {
            LOGGER_UPLOADSERVICEIMPL.error(">>> 删除文件失败 QSException" + e.toString());
            throw new RemoveUploadException("");
        } catch (Exception ex) {
            LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件前删除指定待删除文件异常" + ex.toString());
            throw new RemoveUploadException("");
        }
        return true;
    }

    @Override
    public String uploadResource(UploadInfo uploadInfo) throws UploadException {
        LOGGER_UPLOADSERVICEIMPL.info(">>> uploadResource for " + uploadInfo.getModuleName());
        String imageUrl = null;
        String logicalUrl = null;
        if (uploadInfo.getDataid() != null) {
            String fileName = uploadInfo.getFileName();
            imageUrl = (fileName == null || "".equals(fileName) ? (uploadInfo.getDataid() + "_" + SnowflakeIdWorker.getIns().nextId()) : fileName)
                    + "." + uploadInfo.getExtension();
            logicalUrl = "/" + ConstantBean.SYSTEM_NAME
                    + (VerifyEnvironmentBean.getTestFlag(DealStatus.getShade()) ? "/test" : "")
                    + "/" + uploadInfo.getModuleName()
                    + "/" + uploadInfo.getDataid()
                    + "/" + imageUrl;
        } else {
            imageUrl = SnowflakeIdWorker.getIns().nextId() + "." + uploadInfo.getExtension();
            logicalUrl = "/" + ConstantBean.SYSTEM_NAME
                    + "/" + this.TEMP_PATH
                    + "/" + imageUrl;
        }


        String url = null;
        if (StringUtils.isNotEmpty(uploadInfo.getPicData())) {
            InputStream fileInputStream = null;
            try {
                removeResource(logicalUrl);
            } catch (Exception ex) {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件前删除同名文件异常");
            }

            try {
                if (uploadInfo.getDeletePath() != null) {
                    for (String imgurl : uploadInfo.getDeletePath().split(";")) {
                        removeResource(imgurl);
                    }
                }
            } catch (Exception ex) {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件前删除指定待删除文件异常");
            }

            try {
                /*手机上传的图片为base64加密字符串*/
                byte[] decodedBytes = new BASE64Decoder().decodeBuffer(uploadInfo.getPicData());
                fileInputStream = new ByteArrayInputStream(decodedBytes);
                QingstorService.putFileInputStream(logicalUrl, fileInputStream);
            } catch (QSException e1) {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件失败 QSException");
                LOGGER_UPLOADSERVICEIMPL.error(e1.getMessage());
                throw new UploadException("");
            } catch (FileNotFoundException e) {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件失败 FileNotFoundException");
                LOGGER_UPLOADSERVICEIMPL.error(e.getMessage());
                throw new UploadException("");
            } catch (IOException e) {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件失败 IOException");
                LOGGER_UPLOADSERVICEIMPL.error(e.getMessage());
                throw new UploadException("");
            }
        } else {
            if (StringUtils.isNotEmpty(uploadInfo.getSourcepath())) {
                moveResource(formatUrl(logicalUrl), formatUrl(uploadInfo.getSourcepath()));
            } else {
                LOGGER_UPLOADSERVICEIMPL.error(">>> 上传文件即没有文件流也没有指定移动的文件路径，缺少必要的数据");
                throw new UploadException("缺少必要数据");
            }
        }

        url = QingstorService.getUrl() + logicalUrl;
        return url.replaceAll("\\\\", "/");
    }

    @Override
    public void moveResource(String targetpath, String sourcepath) throws UploadException {
        // TODO Auto-generated method stub
        try {
            QingstorService.moveFile(targetpath, sourcepath);
        } catch (QSException e) {
            // TODO Auto-generated catch block
            LOGGER_UPLOADSERVICEIMPL.error(">>>>> Move File Fail:" + e.getMessage());
            throw new UploadException(e.getMessage());
        }
    }

    @Override
    public void copyResource(String targetpath, String sourcepath) throws UploadException {
        // TODO Auto-generated method stub
        try {
            QingstorService.copyFile(targetpath, sourcepath);
        } catch (QSException e) {
            LOGGER_UPLOADSERVICEIMPL.error(">>>>> Copy File Fail:" + e.getMessage());
            throw new UploadException(e.getMessage());
        }
    }

    /**
     * 将给的路径转化成可操作的路径格式
     *
     * @param url url
     * @return String
     */
    private String formatUrl(String url) {
        if (url.startsWith("https")) {
            if (QingstorService.getUrl().startsWith("https")) {
                url = url.replace(QingstorService.getUrl(), "");
            } else if (QingstorService.getUrl().startsWith("http")) {
                url = url.replace(QingstorService.getUrl().replaceAll("http", "https"), "");
            }
        } else if (url.startsWith("http")) {
            if (QingstorService.getUrl().startsWith("https")) {
                url = url.replace(QingstorService.getUrl().replaceAll("https", "http"), "");
            } else if (QingstorService.getUrl().startsWith("http")) {
                url = url.replace(QingstorService.getUrl(), "");
            }
        }
        if (url.indexOf("\\") > -1) {
            url = url.replaceAll("\\\\", "/");
        }
        return url;
    }
}
